<template>
    <div style="width: 100%; height: 100%; position: relative;">
      <div style="width: 100%; height: 100%" id="chart" ref="chart"></div>
      <div class="legend-container">
        <!-- 展示 tasktype title-->
         <div style="display: flex;flex-direction: column; justify-content: space-between; align-items: center;color: #fff;">
          <span>任务类型：{{ tasktype }}</span>
          <span>状态：{{ title }}</span>
         </div>
      </div>
    </div>
  </template>
  
  <script>
  import * as echarts from "echarts";
  
  export default {
    data() {
      return {
        userData: {},
        chartInstance: null,
        username: ''
      };
    },
    props: {
      tasktype: {
        type: String,
        required: false
      },
      title: {
        type: String,
        required: false
      }
    },
    mounted() {
      // this.initData();
    },
    methods: {
      initData(data,idd,resultData) {
        // '{align_result=[[6972663192, elaine-88-16-94]], accuracy=0.0}'正则提取newData中的elaine-88-16-94
        let username = '';
        if (resultData) {
          const regex = /\[\[.*?, (.*?)\]\]/;
          const match = resultData.match(regex);
          if (match && match[1]) {
            username = match[1];
            this.username = username; // Store the username in the class property
            console.log("Extracted username:", username);
          }
        }
        
        console.log("shenfen")
        this.userData = data;
        if (this.chartInstance) {
          this.chartInstance.dispose();
        }
        this.chartInstance = echarts.init(this.$refs.chart);
        this.getChartOption(idd,resultData);
        //   this.chartInstance.setOption(option);
      },
      getChartOption(idd,resultData) {
        // 处理节点和关系数据
        console.log("this.userDatahhhhhhhhhhhhhhh", this.userData);
        const { nodes, links } = this.processData(this.userData,idd);
        console.log("nodes, linkshhhhhhh", nodes, links);
        const option = {
            title: {
            },
            tooltip: {
              formatter: function(params) {
                if (params.dataType === 'node') {
                  return `
                    <div style="text-align:center; padding: 5px;">
                     <img src="${params.data.avatar}" style="width:60px;height:60px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 10px rgba(0,0,0,0.1)"/><br/>
                      <b>${params.data.name}</b><br/>
                      ID: ${params.data.id}<br/>
                      ${params.data.platform ? '平台: ' + params.data.platform : ''}
                    </div>
                  `;
                }
                return '';
              }
            },
            animationDurationUpdate: 1500,
            animationEasingUpdate: 'quinticInOut',
            series: [{
              type: 'graph',
              layout: 'force',
              force: {
                repulsion: 500,
                edgeLength: 150
              },
              roam: true,
              zoom: 0.6,
              focusNodeAdjacency: true,
              draggable: true,
              data: nodes,
              links: links,
              categories: [
                { name: '中心用户' },
                { name: '微博用户' },
                { name: '知乎用户' },
                { name: '二级关系' },
                { name: '身份匹配' }
              ],
              edgeSymbol: ['none', 'arrow'],
              edgeSymbolSize: [0, 10],
              label: {
                show: true,
                position: 'right',
                formatter: '{b}'
              },
              lineStyle: {
                color: 'source',
                curveness: 0.2
              },
              emphasis: {
                lineStyle: {
                  width: 5
                }
              }
            }]
          };
        this.chartInstance.setOption(option);
  
        // 响应窗口大小变化
        window.addEventListener("resize", () => this.chartInstances.resize());
      },
      
      processData(data,idd) {
          const nodes = [];
          const links = [];
          const nodeSet = new Set();
          debugger;
          console.log("this.rawData",data);
          // 添加中心节点
          const centerNode = {
            id: idd,
            name: data.name,
            symbolSize: [80, 80],
            symbol: `image://${require('@/assets/images/profile1.jpg')}`,
            symbolKeepAspect: true,
            symbolClip: true,
            itemStyle: { color: '#5470c6' },
            category: 0,
            fixed: true,
            x: this.$refs.chart.offsetWidth / 2,
            y: this.$refs.chart.offsetHeight / 2
          };
          nodes.push(centerNode);
          nodeSet.add(idd);
          
          // 添加从resultData提取的username节点
          if (this.username) {
            const usernameNodeId = `username_${this.username}`;
            nodes.push({
              id: usernameNodeId,
              name: this.username,
              symbolSize: 50,
              itemStyle: { color: '#FF3E96' },
              category: 4,
              fixed: true,
              x: this.$refs.chart.offsetWidth / 2 + 1000,
              y: this.$refs.chart.offsetHeight / 2
            });
            nodeSet.add(usernameNodeId);
            
            // 用醒目的连线连接username节点和中心节点
            links.push({
              source: centerNode.id,
              target: usernameNodeId,
              lineStyle: {
                width: 6,
                color: '#FF3E96',
                type: 'solid'
              },
              label: {
                show: true,
                formatter: '身份匹配',
                fontSize: 14,
                fontWeight: 'bold',
                color: '#FF3E96'
              },
             
            });
          }
          
          // 处理微博数据
          data.weiboUserList.forEach(weibo => {
            // 微博源节点（中心用户的微博账号）
            const weiboSourceId = `weibo_${weibo.source.userId}`;
            if (!nodeSet.has(weiboSourceId)) {
              nodes.push({
                id: weiboSourceId,
                name: weibo.source.userNickname || weibo.source.userName,
                symbolSize: 35,
                avatar: weibo.source.avatar,
                itemStyle: { color: '#91cc75' },
                platform: '微博',
                category: 1,
                fixed: true,
                x: this.$refs.chart.offsetWidth / 2 - 1000,
                y: this.$refs.chart.offsetHeight / 2
              });
              nodeSet.add(weiboSourceId);
              
              // 连接中心用户和微博账号
              links.push({
                source: centerNode.id,
                target: weiboSourceId,
                label: {
                  show: true,
                  formatter: '主账号'
                },
                lineStyle: {
                  width: 4,
                  curveness: 0
                }
              });
            }
            
            // 微博目标节点
            const weiboTargetId = `weibo_${weibo.target.userId}`;
            if (!nodeSet.has(weiboTargetId)) {
              nodes.push({
                id: weiboTargetId,
                name: weibo.target.userName,
                avatar: weibo.target.avatar,
                symbolSize: 30,
                itemStyle: { color: '#91cc75' },
                platform: '微博',
                category: 1
              });
              nodeSet.add(weiboTargetId);
            }
            
            // 连接微博源和目标
            links.push({
              source: weiboSourceId,
              target: weiboTargetId
            });
            
            // 处理二级关系
            if (weibo.target.children) {
              weibo.target.children.forEach(child => {
                const childId = `weibo_${child.userId}`;
                if (!nodeSet.has(childId)) {
                  nodes.push({
                    id: childId,
                    name: child.userNickname || child.userName,
                    symbolSize: 25,
                    avatar: child.avatar,
                    itemStyle: { color: '#ee6666' },
                    platform: '微博',
                    category: 3
                  });
                  nodeSet.add(childId);
                }
                
                // 连接目标节点和二级节点
                links.push({
                  source: weiboTargetId,
                  target: childId
                });
              });
            }
          });
          
          // 处理知乎数据
          data.zhihuUserList.forEach(zhihu => {
            // 知乎源节点（中心用户的知乎账号）
            const zhihuSourceId = `zhihu_${zhihu.source.userId}`;
            if (!nodeSet.has(zhihuSourceId)) {
              nodes.push({
                id: zhihuSourceId,
                name: zhihu.source.userNickname || zhihu.source.userName,
                symbolSize: 35,
                avatar: zhihu.source.avatar,
                itemStyle: { color: '#fac858' },
                platform: '知乎',
                category: 2,
                fixed: true,
                x: this.$refs.chart.offsetWidth / 2 + 1000,
                y: this.$refs.chart.offsetHeight / 2
              });
              nodeSet.add(zhihuSourceId);
              
              // 连接中心用户和知乎账号
              links.push({
                source: centerNode.id,
                target: zhihuSourceId,
                label: {
                  show: true,
                  formatter: '主账号'
                },
                lineStyle: {
                  width: 4,
                  curveness: 0
                }
              });
            }
            
            // 知乎目标节点
            const zhihuTargetId = `zhihu_${zhihu.target.userId}`;
            if (!nodeSet.has(zhihuTargetId)) {
              nodes.push({
                id: zhihuTargetId,
                name: zhihu.target.userName,
                avatar: zhihu.target.avatar,
                symbolSize: 30,
                itemStyle: { color: '#fac858' },
                platform: '知乎',
                category: 2
              });
              nodeSet.add(zhihuTargetId);
            }
            
            // 连接知乎源和目标
            links.push({
              source: zhihuSourceId,
              target: zhihuTargetId
            });
          });
          
          return { nodes, links };
        }
    },
  };
  </script>
  
  <style scoped>
  .legend-container {
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: rgba(0, 0, 0, 0.6);
    padding: 10px;
    border-radius: 5px;
    z-index: 1000;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    margin: 5px 0;
  }
  
  .color-box {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid rgba(255, 255, 255, 0.3);
  }
  
  .legend-text {
    color: #fff;
    font-size: 14px;
  }
  </style>
  